<?php
/**
 * 医疗器械专用送货单
 * AUTHOR  : zlf
 * DateTime: 2022/07/27
 */
namespace App\Api\Controllers;

use Illuminate\Http\Request;
use Illuminate\Support\Facades\Validator;
use App\Api\Services\MedicalDeliveryOrderService;
use Illuminate\Support\Facades\DB;
use App\Api\Models\MedicalProductsModel;
use App\Http\Controllers\Api\BaseController;
use App\Api\Models\MedicalDeliveryOrderModel;

class MedicalDeliveryOrderController extends BaseController
{
    /**
     * 添加医疗器械专用送货单
     */
    public function add(Request $request){           
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'customer_name'         =>'string',//客户名称
            'customer_address'      =>'string',//客户地址
            'supply_license_no'     =>'string',//供货单位许可证号         
            'ticket_code'           =>'string',//发票号
            'total_cost'            =>'string',//总金额          
            'total_cost_dx'         =>'string',//总金额大写           
            'handling_person'       =>'string',//送货经手人
            'handling_person_iphone'=>'string',//送货经手人电话
            'delivery_time'         =>'string',//发货时间 
            'consignee'             =>'string',//收货人    
            'consignee_iphone'      =>'string',//收货人电话
            'receiving_time'        =>'string',//收货日期
            'remark'                =>'string',//备注       
            'total_cost'            =>'numeric|min:0',//总费用
        ],[
            'total_cost.numeric'   => '总金额只能为数字',         
            'total_cost.min'       => '总金额最小只能为0',                      
          ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
           
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
    
            if($unit_stamp_files->isValid()){
                 
                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['unit_stamp'] = '/uploads/'.$img_path;
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，有误！','data' => '']);
            }             
        }
        //开启事务
        DB::beginTransaction();        
        try{
            //医疗器械专用送货单
            $dData = $data;           
            $dData['user_id']      = $this->getUserId();
            $dData['main_id']      = $this->getMainUserId();            
            $dData['created_at']   = time();           
            $medical_delivery_id   = MedicalDeliveryOrderService::add($dData);
            /* $data['goods_info']='[
            {"name":"葡萄","type_name":"紫","product_unit":"红富士","price":"5.6","num":"10","serial_number":11,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"name":"水梨","type_name":"黄","product_unit":"砀山梨","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"}
            ]'; */
            //商品详细添加
            if(isset($data['goods_info']) && !empty($data['goods_info'])){
                
                $goodsInfo = json_decode($data['goods_info'],true);
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as &$value){
                                            
                        $value['created_at']          = time();
                        $value['medical_delivery_id'] = $medical_delivery_id;
                        $value['user_id']             = $this->getUserId();
                        $value['main_id']             = $this->getMainUserId();
                    }
                    
                    MedicalProductsModel::insert($goodsInfo);
                }
            }
           
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'添加医疗器械专用送货单');
        }
   
    }
    
    /**
     * 删除医疗器械专用送货单信息
     * @param ids (删除多个逗号分隔)
     */
    public function delete(Request $request){
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'ids'       =>'required',//医疗器械专用送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        }
        
        $id_data = [];
        $id_arr  = explode(',',$data['ids']);
        
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        
        $list = MedicalDeliveryOrderModel::select('id')->where($condition)->whereIn('id',$id_arr)->get()->toArray();
        
        if(!empty($list)){
                     
            foreach ($list as $k=>$v){
            
                $id_data[]=$v['id'];
            }
            
            $bool = MedicalDeliveryOrderModel::where($condition)->whereIn('id',$id_data)->delete();
            
            if($bool){
            
                MedicalProductsModel::where($condition)->whereIn('medical_delivery_id',$id_data)->delete();
            
                return $this->success();
                 
            }else{
                return $this->fail('','删除失败');
            }
        }
          return $this->fail('','医疗器械专用送货单，不存在！');
    }
    
    /**
     * 修改医疗器械专用送货单
     * 
     */
    public function update(Request $request){              
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'medical_delivery_id'   =>'required|integer',//医疗器械专用送货单id
            'customer_name'         =>'string',//客户名称
            'customer_address'      =>'string',//客户地址
            'supply_license_no'     =>'string',//供货单位许可证号         
            'ticket_code'           =>'string',//发票号
            'total_cost'            =>'string',//总金额          
            'total_cost_dx'         =>'string',//总金额大写           
            'handling_person'       =>'string',//送货经手人
            'handling_person_iphone'=>'string',//送货经手人电话
            'delivery_time'         =>'string',//发货时间 
            'consignee'             =>'string',//收货人    
            'consignee_iphone'      =>'string',//收货人电话
            'receiving_time'        =>'string',//收货日期
            'remark'                =>'string',//备注       
            'total_cost'            =>'numeric|min:0',//总费用
        ],[
            'total_cost.numeric'   => '总金额只能为数字',         
            'total_cost.min'       => '总金额最小只能为0',                      
          ]);

        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        $info = MedicalDeliveryOrderService::getMedicalDeliveryOrderInfo(['id'=> $data['medical_delivery_id']]);
         
        if(empty($info)){
             
            return $this->fail('','医疗器械专用送货单号,不存在！');
        }
        if(!empty($unit_stamp_files = $request->file('unit_stamp'))){
        
            if($unit_stamp_files->isValid()){
                 
                $img_path = $unit_stamp_files->store('yz/imgs/'.date('Y').'-'.date('m').'-'.date('d'));
                 
                $data['unit_stamp'] = '/uploads/'.$img_path;
            }else{
                return response()->json(['code' => 1,'msg' => '单位印章，有错误！','data' => '']);
            }   
        }
        //开启事务
        DB::beginTransaction();
        try{
            //医疗器械专用送货单
            $updData = $data;                                
            if(isset($data['deliver_time'])) $updData['deliver_time'] = strtotime($data['deliver_time']);

            $condition['user_id'] = $this->getUserId();
            $condition['main_id'] = $this->getMainUserId();
            $condition['id']      = $updData['medical_delivery_id'];

           /*  $updData['goods_info']='[
            {"goods_id":1,"name":"葡萄888","type_name":"紫8888","product_unit":"红富士888","price":"5.611","num":"1011","serial_number":11,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"goods_id":2,"name":"水梨8888","type_name":"黄888","product_unit":"砀山梨8888","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"},
            {"name":"水梨8888","type_name":"黄888","product_unit":"砀山梨888","price":"3.6","num":"8","serial_number":22,"manufacturer":"掌上网络1","batch_number":"ZS45647547567","date_in_produced":"2022-07-30 21:30:30","effective_date":"2023-07-30 21:30:30","storage_condition":"温度在15度以下","registration_number":"zc3252543253656546"}
            ]'; */
            
            if(isset($updData['goods_info']) && !empty($updData['goods_info'])){
                
                $goodsInfo = json_decode($updData['goods_info'],true);
                
                if(is_array($goodsInfo)){
                    foreach ($goodsInfo as $value){//更新商品信息
                        //更新
                        if(isset($value['goods_id'])){
                            
                            $dCondition['id'] = $value['goods_id'];
                            
                            unset($value['goods_id']);
                            
                            MedicalProductsModel::where($dCondition)->update($value);
                        }else{//添加
                            
                            $value['created_at'] = time();
                            $value['user_id']    = $this->getUserId();
                            $value['main_id']    = $this->getMainUserId();                       
                            $value['medical_delivery_id']= $updData['medical_delivery_id'];
                            
    
                            MedicalProductsModel::insert($value);
                        }
                    }
                }
                unset($updData['goods_info']); unset($updData['medical_delivery_id']);
            }
            $updData['updated_at']   = time();
            $medical_delivery_id = MedicalDeliveryOrderService::update($condition,$updData);
            DB::commit();//提交事务
            return $this->success();
        }catch (Exception $e){
            DB::rollBack();//事务回滚
            //异常响应
            return $this->fail($e->getMessage(),'修改医疗器械专用送货单');
        }
  
    }

    /**
     * 医疗器械专用送货单信息
     * @param medical_delivery_id
     */
    public function find(Request $request){          
        //参数验证
        $validator = Validator::make($data = $request->all(), [        
            'medical_delivery_id'       =>'required|integer',//医疗器械专用送货单id
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg'  => $info,
                'data' => '',
            ]);
        } 
        
        $condition['id']      = $data['medical_delivery_id'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        
        $info = MedicalDeliveryOrderService::getMedicalDeliveryOrderInfo($condition);
        $list = $info;
        if(!empty($info)){
            
            $list['goods_list']= MedicalProductsModel::where(['medical_delivery_id'=>$info['id']])->get();
            
        }
        
       return $this->success($list);
    }
    
    /**
     * 医疗器械专用送货单列表  
     */
    public function MedicalDeliveryOrderList(Request $request){
        
        //参数验证
        $validator = Validator::make($data = $request->all(), [
            'pageSize' =>'required|integer',//页面大小
            'currentPage' =>'required|integer',//当前页
        ]);
        //参数错误响应
        if ($info = $validator->errors()->first()) {
            return response()->json([
                'code' => 1,
                'msg' => $info,
                'data' => '',
            ]);
        }
        
        $id_arr01 = [];
        $id_arr02 = [];
        $medical_delivery_id_arr = [];
        
        $keyword = empty($data['keyword'])?'':$data['keyword'];
        $condition['user_id'] = $this->getUserId();
        $condition['main_id'] = $this->getMainUserId();
        if(!empty($keyword)){
 
            $goodsList = MedicalProductsModel::select('medical_delivery_id')
            ->where($condition)            
            ->where(function($query) use ($keyword) {   
                $query->orWhere('name', 'like', '%'.$keyword.'%');         
                $query->orWhere('type_name', 'like', '%'.$keyword.'%'); 
                $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
            })
            ->orderBy('medical_delivery_id','DESC')
            ->get()->toArray(); 
            
            if(!empty($goodsList)){
                
                foreach ($goodsList as $k=>$v){
                    
                $id_arr01[$k] = $v['medical_delivery_id'];
                
                }
            }
          
            $list = MedicalDeliveryOrderModel::select('id')->where($condition)
                ->where(function($query) use ($keyword) {                
                    $query->orWhere('customer_name', 'like', '%'.$keyword.'%');                  
                    $query->orWhere('customer_address', 'like', '%'.$keyword.'%');
                })->orderBy('id','desc')              
                ->get()->toArray();
                
                if(!empty($list)){
                
                    foreach ($list as $k=>$v){
                
                        $id_arr02[$k] = $v['id'];                
                    }
                }
                
                $medical_delivery_id_arr = array_unique(array_merge($id_arr01,$id_arr02));  
                
                if(empty($medical_delivery_id_arr)){
                
                    $medical_delivery_id_arr[0] ="0";
                }
        }

        $list = MedicalDeliveryOrderService::getList($condition,$medical_delivery_id_arr,$data['pageSize'],$data['currentPage']);

        if(!empty($list['data'])){
            
            foreach ($list['data'] as &$value){
                
                $query = MedicalProductsModel::where('medical_delivery_id',$value['id']);
                
                if(!empty($id_arr01)){
                    
                    $query->where(function($query) use ($keyword) {   
                    $query->orWhere('name', 'like', '%'.$keyword.'%');         
                    $query->orWhere('type_name', 'like', '%'.$keyword.'%');  
                    $query->orWhere('serial_number', 'like', '%'.$keyword.'%');
                    });               
                }
               $value['goods_info'] =  $query->get();
            }
        }
        return $this->success($list);
        
    }
        
}
